package com.example.inventorywarningdemo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.inventorywarningdemo.config.AlertConfig;
import com.example.inventorywarningdemo.dto.EmailDTO;
import com.example.inventorywarningdemo.dto.MaterialDTO;
import com.example.inventorywarningdemo.entity.Order;
import com.example.inventorywarningdemo.entity.Store;
import com.example.inventorywarningdemo.mapper.OrderMapper;
import com.example.inventorywarningdemo.mapper.StoreMapper;
import com.example.inventorywarningdemo.service.AlertService;
import com.example.inventorywarningdemo.service.EmailService;
import com.example.inventorywarningdemo.service.MaterialQueryService;
import com.example.inventorywarningdemo.util.MailUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *预警专用服务
 */
@Service
@RequiredArgsConstructor
public class AlertServiceImpl implements AlertService {
    private final MaterialQueryService materialQueryService;
    private final EmailService emailService;
    private final AlertConfig alertConfig;
    private final StoreMapper storeMapper;
    private final OrderMapper orderMapper;

    /**
     * 检查库存并发送预警邮件
     */
    @Override
    public void checkDailySales() {
        // 获取所有店铺信息
        List<Store> stores = storeMapper.selectList(null);
        if (!stores.isEmpty()) {
            stores.forEach(store -> {
                Long storeId = store.getId();
                //根据订单id查询当日订单销售额总和
                BigDecimal amount = orderMapper.getDailyRevenueByShop(storeId);

                // 计算当日销售额
//                BigDecimal actualSales = calculateDailySales(store.getId());
                // 比较预警值
                if (amount.compareTo(store.getWarningThreshold()) < 0) {
                    store.setDailySales(amount);  // 动态设置销售额用于邮件显示
                    storeMapper.updateById(store);
                }
                EmailDTO emailDTO = buildAlertEmail(stores);
                emailService.sendAlertEmail(emailDTO);
            });

        }
    }

    /**
     * 构建邮件内容
     * @param
     * @return
     */
    private EmailDTO buildAlertEmail(List<Store> stores) {
        String content = stores.stream()
                .map(store -> String.format(
                "店铺名称：%s\n当日营业额：%.2f\n预警阈值：%.2f\n时间：%s",
                store.getStoreName(),
                store.getDailySales(),  // 使用动态计算的销售额
                store.getWarningThreshold(),
                LocalDate.now()))
                .collect(Collectors.joining("\n"));
        return new EmailDTO(
                alertConfig.getToEmail(),
                "【营业额预警】当日店铺营业额不足的清单",
                "以下营业额低于安全阈值：\n\n" + content
        );
    }
}